<style>
	@import "/static/css/wx-index.css";
</style>
<template>
	<view class="container">
		<view class="wechatapp">
			<image class="header" src="/static/img/userAvatar.jpg" />
		</view>
		<view class="auth-title">申请获取以下权限</view>
		<view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
		<view class="login-btn">
			<button class="btn-normal" @tap="getUserInfo">授权登录</button>
		</view>
		<view class="no-login-btn">
			<button class="btn-normal" @tap="onNotLogin">暂不登录</button>
		</view>
		<view v-if="tip" class="tip-layer">
			<view class="tip">{{tipContent}}</view>
		</view>
	</view>
</template>

<script>
	import {
		showTips
	} from '@/static/js/common.js';

	export default {
		data() {
			return {
				httpUrl: "http://fengjian123.com:8080/",
				// httpUrl: "http://localhost:8080/",
				userid: '',
				cookie: '',
				tipContent: '',
				tip: 0,
				allowGetUserInfo: true,
			};
		},
		onLoad() {
			this.getUser();
		},
		methods: {
			getUser: function() {
				let _this = this;
				uni.getStorage({
					key: 'cookie',
					success: function(res) {
						if (res.data.id) {
							_this.userid = res.data.id;
							_this.cookie = res.data;
						} else {
							uni.navigateBack(1);
						}
					},
					fail: function() {
						uni.navigateBack(1);
					}
				});
			},
			getUserInfo: function() {
				let _this = this;
				if (!_this.allowGetUserInfo) return;
				this.allowGetUserInfo = false; // 点击后，不能连续点击
				uni.getUserProfile({
					desc: '用于获取您的个人信息',
					success: (res) => {
						uni.request({
							url: _this.httpUrl + 'private/accredit',
							method: 'POST',
							header: {
								'Content-Type': 'application/json',
								'Authorization': 'Bearer ' + _this.cookie.token,
							},
							data: {
								nickName: res.userInfo.nickName,
								avatarUrl: res.userInfo.avatarUrl,
								userid: _this.userid,
							},
							success: (res) => {
								console.log(res.data.msg)
								if (res.data.err == 0) {
									_this.cookie.login = 1;
									uni.setStorageSync('cookie', _this.cookie);
									uni.reLaunch({
										url: '/pages/user/index',
									});
								} else {
									_this.tips(res.data.msg);
									uni.reLaunch({
										url: '/pages/index/index',
									});
								}
							},
							fail: function(res) {
								console.log(res);
							}
						});
					},
					fail: function(res) {
						console.log(res);
					}
				}).then(() => {
					setTimeout(() => {
						// 在请求成功后2秒重置标志位
						_this.allowGetUserInfo = true;
					}, 2000);
				});
			},
			onNotLogin: function() {
				uni.reLaunch({
					url: '/pages/index/index',
				});
			},
			tips: function(content) {
				showTips(this, content);
			}
		}
	};
</script>